package com.ruoyi.project.ledger.controller;

import java.io.*;
import java.text.SimpleDateFormat;
import java.util.*;

import com.ruoyi.common.utils.SecurityUtils;
import com.ruoyi.framework.security.service.PermissionService;
import com.ruoyi.project.ledger.domain.LedgerFireFightingEquipmentManage;
import com.ruoyi.project.system.domain.SysDept;
import com.ruoyi.project.system.domain.SysUser;
import net.sf.jxls.transformer.XLSTransformer;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Workbook;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import com.ruoyi.framework.aspectj.lang.annotation.Log;
import com.ruoyi.framework.aspectj.lang.enums.BusinessType;
import com.ruoyi.project.ledger.domain.LedgerVehicleFactoryRegistration;
import com.ruoyi.project.ledger.service.ILedgerVehicleFactoryRegistrationService;
import com.ruoyi.framework.web.controller.BaseController;
import com.ruoyi.framework.web.domain.AjaxResult;
import com.ruoyi.common.utils.poi.ExcelUtil;
import com.ruoyi.framework.web.page.TableDataInfo;

/**
 * 治超管理台账Controller
 *
 * @author gwc
 * @date 2020-04-15
 */
@RestController
@RequestMapping("/ledger/registration")
public class LedgerVehicleFactoryRegistrationController extends BaseController
{
    @Autowired
    private ILedgerVehicleFactoryRegistrationService ledgerVehicleFactoryRegistrationService;
    @Autowired
    private PermissionService permissionService;

    /**
     * 查询治超管理台账列表
     */
//    @PreAuthorize("@ss.hasPermi('ledger:registration:list')")
    @GetMapping("/list")
    public TableDataInfo list(LedgerVehicleFactoryRegistration ledgerVehicleFactoryRegistration)
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 场站id
        Long stationId = user.getStationId();
        if(stationId != null){
            ledgerVehicleFactoryRegistration.setStationId(stationId);
        }
        // 管辖区域
        List<String> areaList = user.getAreaList();
        String areas = String.join(",", areaList);
        String managementCharacters = user.getManagementCharacters();
        ledgerVehicleFactoryRegistration.setAreas(areas);
        ledgerVehicleFactoryRegistration.setManagementCharacters(managementCharacters);
        startPage();
        List<LedgerVehicleFactoryRegistration> list = ledgerVehicleFactoryRegistrationService.selectLedgerVehicleFactoryRegistrationList(ledgerVehicleFactoryRegistration);
        return getDataTable(list);
    }

    /**
     * 导出治超管理台账列表
     */
//    @PreAuthorize("@ss.hasPermi('ledger:registration:export')")
    @Log(title = "治超管理台账", businessType = BusinessType.EXPORT)
    @GetMapping("/export")
    public AjaxResult export(LedgerVehicleFactoryRegistration ledgerVehicleFactoryRegistration)
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 场站id
        Long stationId = user.getStationId();
        if(stationId != null){
            ledgerVehicleFactoryRegistration.setStationId(stationId);
        }
        // 管辖区域
        List<String> areaList = user.getAreaList();
        String areas = String.join(",", areaList);
        String managementCharacters = user.getManagementCharacters();
        ledgerVehicleFactoryRegistration.setAreas(areas);
        ledgerVehicleFactoryRegistration.setManagementCharacters(managementCharacters);
        if (ledgerVehicleFactoryRegistration.getCreateTime() == null){
            ledgerVehicleFactoryRegistration.setCreateTime(new Date());
        }
        List<LedgerVehicleFactoryRegistration> list = ledgerVehicleFactoryRegistrationService.selectLedgerVehicleFactoryRegistrationList(ledgerVehicleFactoryRegistration);
        List<LedgerVehicleFactoryRegistration> list1 = new ArrayList<>();
//        List<LedgerVehicleFactoryRegistration> list2 = new ArrayList<>();
        if (list!=null && list.size() >0){
            int j=0;
            int size = list.size();
            for (int i=0; i < size;i=i+2){
                Long aLong = Long.valueOf(++j);
                if (size>i+1){
                    list.get(i).setStationId(aLong);
                    list.get(i).setStationName(String.valueOf(aLong+1));
                    list.get(i).setBeginTime(list.get(i+1).getCarNo());
                    list.get(i).setEndTime(list.get(i+1).getWeight());
                }else {
                    list.get(i).setStationId(aLong);
                    list.get(i).setStationName("");
                    list.get(i).setBeginTime("");
                    list.get(i).setEndTime("");
                }
                list1.add(list.get(i));
            }
        }

        String tplPath =this.getClass().getResource("/").getPath() +"excel/治超管理台账.xls";
        String fileName = "治超管理台账.xls";

        //fileName = FileUtils.setFileDownloadHeader(request, fileName);

        Map<String, Object> beanParams = new HashMap<String, Object>();
        beanParams.put("list", list1);
        beanParams.put("year", new SimpleDateFormat("yyyy").format(ledgerVehicleFactoryRegistration.getCreateTime()));
        beanParams.put("month", new SimpleDateFormat("MM").format(ledgerVehicleFactoryRegistration.getCreateTime()));
        beanParams.put("day", new SimpleDateFormat("dd").format(ledgerVehicleFactoryRegistration.getCreateTime()));

        XLSTransformer former = new XLSTransformer();
        InputStream in = null;
        OutputStream out = null;
        Workbook workbook = null;
        try {
            in = new BufferedInputStream(new FileInputStream(tplPath));
            workbook = former.transformXLS(in, beanParams);
            out = new FileOutputStream(ExcelUtil.getAbsoluteFile(fileName));
            workbook.write(out);
            return AjaxResult.success(fileName);
        } catch (InvalidFormatException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            if (workbook != null)
            {
                try
                {
                    workbook.close();
                }
                catch (IOException e1)
                {
                    e1.printStackTrace();
                }
            }
            if (in != null) {
                try {
                    in.close();
                } catch (IOException e) {
                }
            }
            if (out != null) {
                try {
                    out.close();
                } catch (IOException e) {
                }
            }
        }
        return AjaxResult.error("导出失败");

//        ExcelUtil<LedgerVehicleFactoryRegistration> util = new ExcelUtil<LedgerVehicleFactoryRegistration>(LedgerVehicleFactoryRegistration.class);
//        return util.exportExcel(list, "registration");
    }

    /**
     * 获取治超管理台账详细信息
     */
    /*@PreAuthorize("@ss.hasPermi('ledger:registration:query')")*/
    @GetMapping(value = "/{id}")
    public AjaxResult getInfo(@PathVariable("id") Long id)
    {
        return AjaxResult.success(ledgerVehicleFactoryRegistrationService.selectLedgerVehicleFactoryRegistrationById(id));
    }

    /**
     * 新增治超管理台账
     */
    @PreAuthorize("@ss.hasPermi('ledger:registration:add')")
    @Log(title = "治超管理台账", businessType = BusinessType.INSERT)
    @PostMapping
    public AjaxResult add(@RequestBody LedgerVehicleFactoryRegistration ledgerVehicleFactoryRegistration)
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 判断是否是场站角色
        if(!permissionService.hasRole("admin") && (permissionService.hasRole("station") || permissionService.hasRole("hs_station"))){
            Long stationId = user.getStationId();
            ledgerVehicleFactoryRegistration.setStationId(stationId);
        }else{
            return AjaxResult.error("当前角色无新增权限");
        }
        ledgerVehicleFactoryRegistration.setCreateId(user.getUserId().toString());
        return toAjax(ledgerVehicleFactoryRegistrationService.insertLedgerVehicleFactoryRegistration(ledgerVehicleFactoryRegistration));
    }

    /**
     * 修改治超管理台账
     */
    @PreAuthorize("@ss.hasPermi('ledger:registration:edit')")
    @Log(title = "治超管理台账", businessType = BusinessType.UPDATE)
    @PutMapping
    public AjaxResult edit(@RequestBody LedgerVehicleFactoryRegistration ledgerVehicleFactoryRegistration)
    {
        SysUser user = SecurityUtils.getLoginUser().getUser();
        // 判断是否是场站角色
        if(!permissionService.hasRole("admin") && (permissionService.hasRole("station") || permissionService.hasRole("hs_station"))){
            Long stationId = user.getStationId();
            ledgerVehicleFactoryRegistration.setStationId(stationId);
        }else{
            return AjaxResult.error("当前角色无修改权限");
        }
        ledgerVehicleFactoryRegistration.setUpdateId(user.getUserId().toString());
        return toAjax(ledgerVehicleFactoryRegistrationService.updateLedgerVehicleFactoryRegistration(ledgerVehicleFactoryRegistration));
    }

    /**
     * 删除治超管理台账
     */
    @PreAuthorize("@ss.hasPermi('ledger:registration:remove')")
    @Log(title = "治超管理台账", businessType = BusinessType.DELETE)
	@DeleteMapping("/{ids}")
    public AjaxResult remove(@PathVariable Long[] ids)
    {
        return toAjax(ledgerVehicleFactoryRegistrationService.deleteLedgerVehicleFactoryRegistrationByIds(ids));
    }
}
